package com.example.smartagrisys.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonParser;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 卖家商品实体类
 */
@Slf4j
@Data
@TableName("seller_product")
public class SellerProduct implements Serializable {

    private static final long serialVersionUID = 1L;
    
    // 配置ObjectMapper
    private static final ObjectMapper objectMapper = new ObjectMapper()
        .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true) // 允许单引号
        .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) // 允许未引用的字段名
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知属性

    /**
     * 商品ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 卖家ID
     */
    private Long sellerId;

    /**
     * 卖家名称
     */
    private String sellerName;

    /**
     * 商品编号
     */
    private String productCode;

    /**
     * 商品名称
     */
    private String name;

    /**
     * 商品分类
     */
    private String category;

    /**
     * 商品价格
     */
    private BigDecimal price;

    /**
     * 计量单位
     */
    private String unit;

    /**
     * 库存数量
     */
    private Integer stock;

    /**
     * 商品图片
     */
    private String image;

    /**
     * 商品描述
     */
    private String description;

    /**
     * 产地
     */
    private String origin;

    /**
     * 生产日期
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime productionDate;

    /**
     * 保质期(天)
     */
    private Integer shelfLife;

    /**
     * 品质证书 - 数据库中存储为JSON字符串
     */
    private String certificates;
    
    /**
     * 证书列表 - 用于前端传输
     */
    @TableField(exist = false)
    private List<String> certificatesList;
    
    /**
     * 获取证书列表
     */
    public List<String> getCertificatesList() {
        if (certificatesList != null) {
            return certificatesList;
        }
        
        if (certificates == null || certificates.isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            // 首先检查是否是JSON格式
            if (certificates.startsWith("[") && certificates.endsWith("]")) {
                certificatesList = objectMapper.readValue(certificates, new TypeReference<List<String>>() {});
            } else {
                // 直接处理为逗号分隔的字符串
                certificatesList = new ArrayList<>();
                if (certificates.contains(",")) {
                    certificatesList.addAll(Arrays.asList(certificates.split(",")));
                } else {
                    certificatesList.add(certificates.trim());
                }
            }
            return certificatesList;
        } catch (Exception e) {
            log.error("解析certificates字段失败: {}", certificates, e);
            // 备选处理方式
            certificatesList = new ArrayList<>();
            if (certificates.contains(",")) {
                certificatesList.addAll(Arrays.asList(certificates.split(",")));
            } else {
                certificatesList.add(certificates.trim());
            }
            return certificatesList;
        }
    }
    
    /**
     * 设置证书列表，同时更新certificates字符串
     */
    public void setCertificatesList(List<String> certificatesList) {
        this.certificatesList = certificatesList;
        
        try {
            if (certificatesList != null && !certificatesList.isEmpty()) {
                this.certificates = objectMapper.writeValueAsString(certificatesList);
                log.debug("设置certificates为: {}", this.certificates);
            } else {
                this.certificates = "[]";
            }
        } catch (Exception e) {
            log.error("转换certificatesList为JSON字符串失败", e);
            this.certificates = "[]";
        }
    }

    /**
     * 养分含量
     */
    private String nutrientContent;

    /**
     * 适用作物 - 数据库中存储为JSON字符串
     */
    private String suitableCrops;
    
    /**
     * 适用作物列表 - 用于前端传输
     */
    @TableField(exist = false)
    private List<String> suitableCropsList;
    
    /**
     * 获取适用作物列表
     */
    public List<String> getSuitableCropsList() {
        if (suitableCropsList != null) {
            return suitableCropsList;
        }
        
        if (suitableCrops == null || suitableCrops.isEmpty()) {
            return new ArrayList<>();
        }
        
        try {
            // 首先检查是否是JSON格式
            if (suitableCrops.startsWith("[") && suitableCrops.endsWith("]")) {
                suitableCropsList = objectMapper.readValue(suitableCrops, new TypeReference<List<String>>() {});
            } else {
                // 直接处理为逗号分隔的字符串
                suitableCropsList = new ArrayList<>();
                if (suitableCrops.contains(",")) {
                    suitableCropsList.addAll(Arrays.asList(suitableCrops.split(",")));
                } else {
                    suitableCropsList.add(suitableCrops.trim());
                }
            }
            return suitableCropsList;
        } catch (Exception e) {
            log.error("解析suitableCrops字段失败: {}", suitableCrops, e);
            // 备选处理方式
            suitableCropsList = new ArrayList<>();
            if (suitableCrops.contains(",")) {
                suitableCropsList.addAll(Arrays.asList(suitableCrops.split(",")));
            } else {
                suitableCropsList.add(suitableCrops.trim());
            }
            return suitableCropsList;
        }
    }
    
    /**
     * 设置适用作物列表，同时更新suitableCrops字符串
     */
    public void setSuitableCropsList(List<String> suitableCropsList) {
        this.suitableCropsList = suitableCropsList;
        
        try {
            if (suitableCropsList != null && !suitableCropsList.isEmpty()) {
                this.suitableCrops = objectMapper.writeValueAsString(suitableCropsList);
                log.debug("设置suitableCrops为: {}", this.suitableCrops);
            } else {
                this.suitableCrops = "[]";
            }
        } catch (Exception e) {
            log.error("转换suitableCropsList为JSON字符串失败", e);
            this.suitableCrops = "[]";
        }
    }

    /**
     * 使用说明
     */
    private String instructions;

    /**
     * 上架状态：0-下架，1-上架
     */
    private Integer status;

    /**
     * 销量
     */
    private Integer sales;

    /**
     * 备注信息
     */
    private String remark;

    /**
     * 创建时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime updateTime;
    
    /**
     * 初始化数组字段
     * 用于Bean初始化后确保数组字段有值
     */
    public void initArrayFields() {
        if (this.certificatesList == null) {
            this.getCertificatesList();
        }
        
        if (this.suitableCropsList == null) {
            this.getSuitableCropsList();
        }
    }
}
